<template>
  <view>
    <view class="p-lr-20 relative">
      <u-navbar title="选择备件" :background="{ backgroundColor: '#9CE0FF' }" :border-bottom="false" title-color="#000" title-size="37" />
      <view class="ml-20 mr-20 mt-30">

        <u-search :clearabled="true"
                  shape="square"
                  input-align="left"
                  :input-style="{ 'fontSize': '32rpx' }"
                  placeholder-color="#888"
                  border-color="#888"
                  bg-color="#fff"
                  :show-action="false"
                  height="80"
                  placeholder="搜索备件名、备件编号、条形码编号"
                  v-model="queryParams.searchValue"
                  @search="doQuery"></u-search>
      </view>
      <view>
        <view class="flex justify-center w-full">
          <empty-icon v-if="!dataList.length && !loading"></empty-icon>
        </view>

        <view class="flex w-full flex-column mt-20">
          <view class="w-full flex align-center mb-30" v-for="item in dataList" :key="item.partId">
            <u-checkbox class="w-full border-888888 br-10 pl-25" active-color="#19BE6B" size="40" label-size="32" :name="item.partId" :value="isExistInSelection(item.partId)" @change="selectPart">
              <!-- 图片缩略图 -->
              <view class="flex align-center">
                <view v-if="item.photoFiles && item.photoFiles.length>0" class="max-h-150 max-w-150">
                  <image class="h-150 w-150" :data-cur="item.photoFiles[0].link" :src="item.photoFiles[0].link" />
                </view>

                <view v-else class="w-150 h-150 bg-CCCCCC flex flex-column align-center justify-center">
                  <image class="w-47 h-40" src="@/static/images/common/empty.png"></image>
                  <text class="color-fff fz-24 lh-33 mt-10">无备件图片</text>
                </view>
                <view class="ml-50 flex justify-between flex-column">
                  <view class="color-333333 fz-32 max-w-390">{{ item.partName || '' }}</view>
                  <view class="fz-24 color-CCCCCC">无条形码库存: {{ item.normalStock || 0 }}</view>
                  <view class="fz-24 color-CCCCCC">条形码库存{{ item.barcodeStock || 0 }} </view>
                </view>
              </view>

            </u-checkbox>
          </view>
        </view>
      </view>
    </view>

    <view class=" h-235 sticky bottom0 bg-fff flex align-center justify-end">
      <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-2D8CF0 lh-60 text-center mr-50" @tap="cancel">
        <text>取消</text>
      </view>
      <view class="h-60 w-120 br-5 border-2D8CF0 fz-28 color-fff lh-60 text-center bg-2D8CF0 mr-50" @tap="confirm">
        <text>提交</text>
      </view>
    </view>

    <!--未选择模态框-->
    <u-modal border-radius="20" :show-confirm-button="false" :show-title="false" mask-close-able v-model="emptyModel">
      <view class="h-150 flex align-center justify-center font-bold fz-30">
        <image class="mr-20 w-38 h-38" src="@/static/images/mine/error.png"></image>
        <text>请选择备件</text>
      </view>
    </u-modal>

  </view>
</template>

<script>
import EmptyIcon from "@/components/EmptyIcon/EmptyIcon";
import {partSearch , partAttachList} from '@/api/spare/part'

export default {
  name: 'ChoosePart',
  components: { EmptyIcon },
  data () {
    return {
      queryParams: {
        hospitalId: '',
        warehouseId: '',
        searchValue: '',
      },
      noMore: false,
      dataList: [],
      emptyModel: false,
      loading: true,
      selection: [],
      allowEmpty: true,
    }
  },
  computed: {
    loadMoreStatus() {
      if (this.loading) {return 'loading'}
      if (this.noMore) {return 'nomore'}
      return 'loadmore'
    },
    queryParamsWithPartId() {
      return {
        ...this.queryParams,
        partId: this.dataList.length ? this.dataList[this.dataList.length - 1].partId : '',
      }
    },
    isExistInSelection() {
      return (partId) => this.selection.some(item => item.partId === partId)
    },
  },
  onReachBottom() {
    if (this.loadMoreStatus === 'loadmore') {
      this.getList()
    }
  },
  onLoad() {
    this.resetQueryParams()
    this.resetNoMore()
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('allowEmpty', value => this.allowEmpty = value)
    Promise.all([
      new Promise(resolve => {
        eventChannel.on('hospitalId', hospitalId => {
          this.queryParams.hospitalId = hospitalId
          resolve(hospitalId)
        })
      }),
      new Promise(resolve => {
        eventChannel.on('companyId', companyId => {
          this.queryParams.warehouseId = companyId
          resolve(companyId)
        })
      }),
      new Promise(resolve => {
        eventChannel.on('selection', selection => {
          this.selection = selection || []
          resolve(selection)
        })
      }),
    ]).then(() => {
      this.doQuery()
    })
  },
  methods: {
    resetQueryParams() {
      this.queryParams = {
        hospitalId: '',
        warehouseId: '',
        searchValue: '',
      }
    },
    resetNoMore() {
      this.noMore = false
    },
    async doQuery() {
      this.loading = true
      try {
        const {data: dataList} = await partSearch(this.queryParams)
        const dataWithImgList = await Promise.all(dataList.map(item =>
          partAttachList(item.partId).then(attach => Promise.resolve({
            ...item,
            photoFiles: attach.data
          }))
        ))
        this.dataList = dataWithImgList
        this.noMore = dataWithImgList.length < 10
        this.loading = false
        return Promise.resolve(this.dataList)
      } catch(e) {
        this.loading = false
        return Promise.reject(e)
      }
    },
    async getList() {
      this.loading = true
      try {
        const {data: dataList} = await partSearch(this.queryParamsWithPartId)
        const dataWithImgList = await Promise.all(dataList.map(item =>
          partAttachList(item.partId).then(attach => Promise.resolve({
            ...item,
            photoFiles: attach.data
          }))
        ))
        this.dataList = this.dataList.concat(dataWithImgList)
        this.noMore = dataWithImgList.length < 10
        this.loading = false
        return Promise.resolve(this.dataList)
      } catch(e) {
        this.loading = false
        return Promise.reject(e)
      }
    },
    selectPart({value, name: partId}) {
      if (!value) {
        const index = this.selection.findIndex(item => item.partId === partId)
        this.selection.splice(index, 1)
        return
      }
      const part = this.dataList.find(item => item.partId === partId)
      if (part) {
        this.selection.push(part)
      }
    },
    cancel () {
      uni.navigateBack({delta: 1});
    },
    confirm() {
      if (!this.allowEmpty && this.selection.length === 0) {
        this.emptyModel = true
        return
      }
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('confirm', this.selection)
      uni.navigateBack({delta: 1})
    }
  },
}
</script>
<style lang="scss">
page {
  background-color: #FFFFFF;
}
</style>

<style lang="scss" scoped>
/deep/ .u-radio__label {
  margin-left: 20rpx !important;
  padding: 24rpx 0 24rpx 24rpx !important;
  flex: 1 !important;
  width: 560rpx;
}

/deep/ .u-radio {
  width: 100% !important;
  display: flex !important;
  line-height: 1;
}

/deep/ .u-input__input {
  font-size: 32rpx !important;
}

/deep/ .uicon-search {
  font-size: 20px !important;
}
</style>
